﻿using Gecko;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WinApp.Services;

namespace WinApp
{
    public partial class HomePage1 : Form
    {
        public HomePage1()
        {
            this.Load += HomePage_InitializeComponent;


            this.MinimumSize = new Size
            {
                Width = 880,
                Height = 504
            };
            //this.TopMost = true;

            InitializeComponent();

            //this.TopMost = true;
            //图标显示在托盘区
            notifyIcon.Visible = true;




            //Geckofx通过自签名证书
            geckoWebBrowser1.NSSError += geckoWebBrowser1_NSSError;
            geckoWebBrowser1.Navigate(Config.HomeUrl);



        }


        /// <summary>
        /// Geckofx通过自签名证书
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void geckoWebBrowser1_NSSError(object sender, Gecko.Events.GeckoNSSErrorEventArgs e)
        {
            if (e.Message.Contains("Certificate"))
            {
                //Gecko.CertOverrideService.GetService().RememberRecentBadCert(e.Uri, e.SSLStatus);
                //geckoWebBrowser1.Navigate(e.Uri.AbsoluteUri);
                //e.Handled = true;
            }

        }
        //GeckoWebBrowser firefox;

        #region//创建对象及声明变量
        //创建NotifyIcon对象
        NotifyIcon notifyIcon = new NotifyIcon();
        //创建托盘图标对象
        Icon ico = new Icon(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "img", "favicon_small.ico"));
        //创建托盘菜单对象
        ContextMenu notifyContextMenu = new ContextMenu();
        #endregion

        private void HomePage_Load(object sender, EventArgs e)
        {
            GeckoJsToCsHelper.Initialize();
            this.Text = "芯聊";

            Gecko.LauncherDialog.Download += LauncherDialog_Download;

            GeckoJsToCsHelper.Initialize(this.geckoWebBrowser1);
            SimHelper.Initialize(timer1, notifyIcon1);
            SimHelper.Initialize(geckoWebBrowser1);
            //geckoWebBrowser1
            //鼠标恢复默认
            this.Cursor = Cursors.Default;

            //设置鼠标放在托盘图标上面的文字
            this.notifyIcon1.Text = "芯聊";
            this.Activated += HomePage1_Activated;
            this.Deactivate += HomePage1_Deactivate;


        }

        private void HomePage1_Deactivate(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(SimHelper.Account))
            {
                Console.WriteLine($"当前时间(Deactivate)：{DateTime.Now}:{SimHelper.Number}");
                //if (sender is Form form)
                //{
                //    form.Select();
                //    form.Activate();
                //}
                //GeckoHelper.GetMessage(int.MinValue);


            }
        }

        private void HomePage1_Activated(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(SimHelper.Account))
            {
                GeckoHelper.GetMessage1(SimHelper.Number);
                Console.WriteLine($"当前时间(Activated)：{DateTime.Now}:{SimHelper.Number}");
            }
        }

        /// <summary>
        /// 下载设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LauncherDialog_Download(object sender, LauncherDialogEvent e)
        {
            uint flags = (uint)nsIWebBrowserPersistConsts.PERSIST_FLAGS_NO_CONVERSION |
         (uint)nsIWebBrowserPersistConsts.PERSIST_FLAGS_REPLACE_EXISTING_FILES |
         (uint)nsIWebBrowserPersistConsts.PERSIST_FLAGS_BYPASS_CACHE;

            SaveFileDialog dlg = new SaveFileDialog
            {
                FileName = e.Filename
            };
            if (dlg.ShowDialog(this.ParentForm) == DialogResult.OK)
            {
                nsIURI source = IOService.CreateNsIUri(e.Url);
                nsIURI dest = IOService.CreateNsIUri(new Uri(dlg.FileName).AbsoluteUri);
                nsAStringBase t = new nsAString(Path.GetFileName(dlg.FileName));

                nsIWebBrowserPersist persist = Xpcom.CreateInstance<nsIWebBrowserPersist>("@mozilla.org/embedding/browser/nsWebBrowserPersist;1");

                nsITransfer nst = Xpcom.CreateInstance<nsITransfer>("@mozilla.org/transfer;1");
                nst.Init(source, dest, t, e.Mime, 0, null, persist, false);

                if (nst != null)
                {
                    persist.SetPersistFlagsAttribute(flags);
                    persist.SetProgressListenerAttribute(nst);
                    try
                    {
                        persist.SaveURI(source, null, null, (uint)Gecko.nsIHttpChannelConsts.REFERRER_POLICY_NO_REFERRER, null, null, (nsISupports)dest, null);

                        //MessageBox.Show($"文件[{Path.GetFileName(dlg.FileName)}]已下载成功!");
                        //GuiHelper.MsgBox($"文件[{Path.GetFileName(dlg.FileName)}]已下载成功!");
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"下载失败: {ex.Message}.");
                        //GuiHelper.MsgBox($"下载失败: {ex.Message}.");
                    }
                    return;
                }
                MessageBox.Show($"下载失败: 服务器无响应...");


            }
        }

        private void HomePage_InitializeComponent(object sender, EventArgs e)
        {
            CheckForIllegalCrossThreadCalls = false;
        }

        /// <summary>
        /// 隐藏任务栏图标，显示托盘图标(最小化按钮显示在托盘区)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HomePage_SizeChanged(object sender, EventArgs e)
        {
            ////判断是否选择的是最小化按钮
            //if (WindowState == FormWindowState.Minimized)
            //{
            //    //托盘显示图标等于托盘图标对象
            //    //注意notifyIcon1是控件的名字而不是对象的名字
            //    notifyIcon1.Icon = ico;
            //    //隐藏任务栏区图标
            //    this.ShowInTaskbar = false;
            //    //图标显示在托盘区
            //    notifyIcon.Visible = true;

            //}


            //if (WindowState == FormWindowState.Minimized)
            //{
            //    this.TopMost = false;
            //    SimHelper.Initialize(this);

            //}
            //else
            //{
            //    this.TopMost = true;
            //    SimHelper.Initialize(this);

            //}
        }

        private Icon icon1 = new Icon(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "img", "favicon_small.ico"));
        private Icon icon2 = new Icon(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "img", "small_kong.ico"));

        int i = 0;

        /// <summary>
        /// 当指定的计时器间隔已过去而且计时器处于启用状态时发生。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            SimHelper.Inti(this.Handle);

            SimHelper.Inti(this);

            if (this.timer1.Enabled == true)
            {
                SimHelper.flashTaskBar(this.Handle, SimHelper.falshType.FLASHW_TIMERNOFG);
            }
            else
            {
                SimHelper.flashTaskBar(SimHelper.IntPtr, SimHelper.falshType.FLASHW_STOP);
            }
            //如果i=0则让任务栏图标变为透明的图标并且退出
            if (i < 1)
            {
                this.notifyIcon1.Icon = icon2;
                i++;
                return;
            }
            //如果i!=0,就让任务栏图标变为ico1,并将i置为0;
            else
                this.notifyIcon1.Icon = icon1;
            i = 0;
        }

        #region 退出系统
        //protected override void WndProc(ref Message message)
        //{
        //    if (message.Msg == 0x0112 && ((int)message.WParam == 0xF060))
        //    {
        //        ////点击右上角X按钮后要执行的代码
        //        //if (SimHelper.Account != "")
        //        //{
        //        //    var url = Config.ApiUrl + $"/api/v1/account/logout/{SimHelper.Account}/2";

        //        //    var msg = Services.Common.Tools.HttpGet(url);
        //        //    if (!string.IsNullOrWhiteSpace(msg))
        //        //    {
        //        //        var result = JObject.Parse(msg);
        //        //        var status = result["code"].Value<int>();
        //        //        if (status != 200)
        //        //        {
        //        //            MessageBox.Show("退出登录失败，报错原因" + status);
        //        //        }
        //        //    }
        //        //}
        //    }
        //}



        //const int WM_SYSCOMMAND = 0x112;
        //const int SC_CLOSE = 0xF060;
        //const int SC_MINIMIZE = 0xF020;
        //const int SC_MAXIMIZE = 0xF030;
        //const int SC_RESTORE = 61728;

        //protected override void WndProc(ref Message message)
        //{
        //    //if (message.WParam.ToInt32() == 0xF020)  //拦截最小化按钮
        //    //{
        //    //    GeckoHelper.GetMessage(SimHelper.Number);
        //    //}
        //    if (message.Msg == WM_SYSCOMMAND)
        //    {
        //        if (message.WParam.ToInt32() == SC_RESTORE)
        //        {
        //            GeckoHelper.GetMessage1(SimHelper.Number);
        //            Console.WriteLine("当前时间：" + DateTime.Now + "调用此处方法：" + SimHelper.Number);
        //        }
        //    }

        //   //else if (!string.IsNullOrWhiteSpace(SimHelper.Account) && message.Msg == 127)
        //   // {
        //   //     Console.WriteLine(message.Msg);
        //   //     GeckoHelper.GetMessage1(SimHelper.Number);
        //   // }

        //    base.WndProc(ref message);
        //}

        #endregion

        /// <summary>
        /// 关闭窗体（方法里：到右下角）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HomePage1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //取消关闭窗口
            e.Cancel = true;
            //最小化主窗口
            this.WindowState = FormWindowState.Minimized;

            //注意notifyIcon1是控件的名字而不是对象的名字
            notifyIcon1.Icon = ico;
            //隐藏任务栏区图标
            this.ShowInTaskbar = false;
            ////图标显示在托盘区
            //notifyIcon.Visible = true;
        }

        /// <summary>
        /// 退出登录，注意要指定notifyIcon1.ContextMenuStrip =myMenu(没有这句的话，右键托盘图标，菜单是出不来的)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            #region 退出系统
            if (SimHelper.Account != "")
            {
                var url = Config.ApiUrl + $"/api/v1/account/logout/{SimHelper.Account}/2";

                var msg = Services.Common.Tools.HttpGet(url);
                if (!string.IsNullOrWhiteSpace(msg))
                {
                    var result = JObject.Parse(msg);
                    var status = result["code"].Value<int>();
                    if (status != 200)
                    {
                        MessageBox.Show("退出登录失败，报错原因" + status);
                    }
                    else
                    {
                        this.Dispose();
                        this.Close();
                    }
                }
            }
            #endregion
            else
            {
                this.Dispose();
                this.Close();
            }

            //Application.Exit();
        }

        /// <summary>
        /// 单击右下角左键显示页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            //判断是否已经最小化于托盘
            if (WindowState == FormWindowState.Minimized)
            {
                if (e.Button == MouseButtons.Left && e.Clicks == 0)
                {
                    //还原窗体显示
                    WindowState = FormWindowState.Normal;
                    //激活窗体并给予它焦点
                    this.Activate();

                    //任务栏区显示图标
                    this.ShowInTaskbar = true;
                    ////托盘区图标隐藏
                    //notifyIcon.Visible = false;
                }
            }

        }
    }
}
